<template>
  <el-table :data="formatData" :row-style="showRow" v-bind="$attrs">
    <el-table-column type="expand">
      <template slot-scope="props">
        <el-table v-if="props.row.children" :data="props.row.children" class="c-child-table">
          <el-table-column v-for="(childcolumn, index) in childrenColumns" :key="index" :prop="childcolumn.value" :label="childcolumn.text" :width="childcolumn.width">
            <template slot-scope="scope">
              {{ scope.row[childcolumn.value] }}
              <!-- 自定义列 -->
              <slot :props="scope" :propConfig="childcolumn" name="child-td-cell"/>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-table-column>
    <el-table-column v-for="(column, index) in columns" :key="index" :label="column.text" :width="column.width">
      <template slot-scope="scope">
        {{ scope.row[column.value] }}
        <!-- 自定义列 -->
        <slot :props="scope" :propConfig="column" name="td-cell"/>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import treeToArray from './eval'
export default {
  name: 'TableInTable',
  props: {
    /* eslint-disable */
    data: {
      type: [Array, Object],
      required: true
    },
    columns: {
      type: Array,
      default: () => []
    },
    childrenColumns: {
      type: Array,
      default: () => []
    },
    evalFunc: Function,
    evalArgs: Array,
    expandAll: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    // 格式化数据源
    formatData: function() {
      let tmp
      if (!Array.isArray(this.data)) {
        tmp = [this.data]
      } else {
        tmp = this.data
      }
      const func = this.evalFunc || treeToArray
      const args = this.evalArgs ? Array.concat([tmp, this.expandAll], this.evalArgs) : [tmp, this.expandAll]
      return func.apply(null, args)
    },
    
  },
  methods: {
    showRow: function(row) {
      const show = (row.row.parent ? (row.row.parent._expanded && row.row.parent._show) : true)
      row.row._show = show
      return show ? 'animation:treeTableShow 1s;-webkit-animation:treeTableShow 1s;' : 'display:none;'
    },
    // 格式化子数据源
    formatChildData: function(data) {
      let tmp
      if (!Array.isArray(data)) {
        tmp = [data]
      } else {
        tmp = data
      }
      const func = this.evalFunc || treeToArray
      const args = this.evalArgs ? Array.concat([tmp, this.expandAll], this.evalArgs) : [tmp, this.expandAll]
      return func.apply(null, args)
    }
  }
}
</script>

<style lang="scss" scoped>
  .c-child-table{
    border: 1px solid #ebeef5;
    border-bottom: none;
  }
</style>

